package ${projectDomain}.aop;

import java.util.List;
import java.util.stream.Collectors;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.unswift.annotation.api.Api;
import com.unswift.annotation.api.ApiField;
import com.unswift.annotation.api.ApiMethod;
import ${projectDomain}.annotation.request.Auth;
import ${projectDomain}.core.CommonOperator;
import ${projectDomain}.pojo.cho.login.TokenResourceCho;
import ${projectDomain}.pojo.cho.login.TokenUserCho;
import com.unswift.utils.ExceptionUtils;
import com.unswift.utils.ObjectUtils;

@Aspect
@Component
@Api(value="权限AOP，负责处理@Auth注解", author = "unswift", date = "2023-10-05", version = "1.0.0")
public class AuthAop extends CommonOperator{

	@ApiMethod("权限aop的切面规则")
	@Pointcut("@annotation(${projectDomain}.annotation.request.Auth)")
	public void entryAuthPoint() {
	}
	
	@ApiMethod(value="权限aop的切面实现", params = {@ApiField("切面的方法封装"), @ApiField("权限注解")})
	@Around("entryAuthPoint() && @annotation(auth)")
	public Object around(ProceedingJoinPoint point, Auth auth) throws Throwable {
		TokenUserCho user=(TokenUserCho)this.getUser();
		ExceptionUtils.empty(user, "login.failure");
		List<TokenResourceCho> resourceList = user.getResourceList();
		ExceptionUtils.empty(resourceList, "permission.denied");
		List<Long> authResourceList = resourceList.stream().filter(r -> ObjectUtils.contains(auth.value(), r.getAuthKey())).map(r -> r.getId()).collect(Collectors.toList());
		ExceptionUtils.trueException(authResourceList.size()==0, "permission.denied");
//		long authResourceId=authResourceList.get(0);
//		List<Long> roleIds=user.getRoleList().stream().map(r -> r.getId()).collect(Collectors.toList());
		
		
		Object result = point.proceed();
		
		
		return result;
	}
}
